// src/models/role.ts
import mongoose, { Document, Schema } from 'mongoose'
import { Counter } from './counter'
import dayjs from 'dayjs'

export interface IPermission {
  key: string
  label: string
  path: string
  id?: string
  parent_id?: number
  sort?: number
  icon?: string
}

export interface IRole extends Document {
  id: number
  name: string
  code: string
  description: string
  permissions: IPermission[]
  created_at: string
  updated_at: string
  created_by: number | null
  updated_by: number | null
}

const RoleSchema: Schema = new Schema({
  id: {
    type: Number,
    unique: true,
    description: '角色id'
  },
  name: {
    type: String,
    unique: true,
    required: true,
    description: '角色名称'
  },
  code: {
    type: String,
    unique: true,
    required: true,
    description: '角色编码，用于系统标识'
  },
  description: {
    type: String,
    required: false,
    default: '',
    description: '角色描述'
  },
  permissions: {
    type: [
      {
        key: { type: String, required: true },
        label: { type: String, required: true },
        path: { type: String, required: true },
        id: { type: String },
        parent_id: { type: Number },
        sort: { type: Number },
        icon: { type: String }
      }
    ],
    default: [],
    description: '菜单权限列表'
  },
  created_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '创建时间'
  },
  updated_at: {
    type: String,
    default: () => dayjs().format('YYYY-MM-DD HH:mm:ss'),
    description: '最后更新时间'
  },
  created_by: {
    type: Number,
    default: null,
    description: '创建者id'
  },
  updated_by: {
    type: Number,
    default: null,
    description: '最后更新者id'
  }
})

// 保存前处理
RoleSchema.pre<IRole>('save', async function (next) {
  if (this.isNew) {
    try {
      const counter = await Counter.findByIdAndUpdate(
        { _id: 'role_id' },
        { $inc: { seq: 1 } },
        { new: true, upsert: true }
      )
      this.id = counter.seq
      next()
    } catch (error: any) {
      next(error)
    }
  } else {
    next()
  }
})

// 更新时更新时间戳
RoleSchema.pre<IRole>('findOneAndUpdate', function (next) {
  this.set({ updated_at: dayjs().format('YYYY-MM-DD HH:mm:ss') })
  next()
})

// 添加这段代码来配置 toJSON
RoleSchema.set('toJSON', {
  transform: function (doc, ret) {
    const { _id, __v, ...rest } = ret
    return rest
  }
})

export const Role = mongoose.model<IRole>('role', RoleSchema, 'role')
